const Koa = require('koa')
const app = new Koa()
const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const koaJwt = require('koa-jwt')
const cors = require('koa2-cors')

const InitManager = require('./utils/init');
const Mongodb = require('./model/index');
const Constant = require('./utils/constant')
const Middlewares = require('./utils/middlewares');
const Sess = require('./utils/sess');
const resModel = require('./utils/resModel');
// error handler
onerror(app)

let authUrl = ['login', 'register', 'logout']

app.use(async(ctx, next)=>{
  let token = ctx.headers.authorization;
  let url = ctx.request.url;
  let _isAuthUrl = false;
  for (let i = 0; i < authUrl.length;i++) {
    if (url.indexOf(authUrl[i]) >0) {
      _isAuthUrl = true;
      break;
    }
  }
  if (_isAuthUrl) {
    await next();
  } else {
    return sess.autoToken(ctx, next)
  }
});
 
app.use(koaJwt({
secret : Constant.security.secretKey
}).unless({
  path:[/\/register/, /\/login/, /\/logout/]
}));
// middlewares
app.use(cors())
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

app.use(Middlewares.catchError)

InitManager.initCore(app);
for(let key in Constant) {
  global[key] = Constant[key]
}
global.sess = Sess;
global.resModel = resModel;
// logger
app.use(async (ctx, next) => {
  const start = new Date()
  await next()
  const ms = new Date() - start
  console.log(`${ctx.method} ${ctx.url} - ${ms}ms`)
})

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app
